package com.example.jobtask.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.example.jobtask.entity.JobTask;
import com.example.jobtask.service.JobTaskService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 任务管理REST API控制器 - 仅管理员可访问
 */
@RestController
@RequestMapping("/api/tasks")
@CrossOrigin(origins = "*")
@SaCheckLogin
@SaCheckRole("ADMIN")
public class JobTaskController {
    
    @Autowired
    private JobTaskService jobTaskService;
    
    /**
     * 创建任务
     */
    @PostMapping
    public ResponseEntity<?> createTask(@Valid @RequestBody JobTask jobTask) {
        try {
            JobTask createdTask = jobTaskService.createTask(jobTask);
            return ResponseEntity.ok(ApiResponse.success("任务创建成功", createdTask));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("创建任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新任务
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateTask(@PathVariable Long id, @Valid @RequestBody JobTask jobTask) {
        try {
            JobTask updatedTask = jobTaskService.updateTask(id, jobTask);
            return ResponseEntity.ok(ApiResponse.success("任务更新成功", updatedTask));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("更新任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTask(@PathVariable Long id) {
        try {
            jobTaskService.deleteTask(id);
            return ResponseEntity.ok(ApiResponse.success("任务删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("删除任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取任务
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getTaskById(@PathVariable Long id) {
        try {
            return jobTaskService.getTaskById(id)
                    .map(task -> ResponseEntity.ok(ApiResponse.success("获取任务成功", task)))
                    .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND)
                            .body(ApiResponse.error("任务不存在")));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取所有任务（分页）
     */
    @GetMapping
    public ResponseEntity<?> getAllTasks(Pageable pageable) {
        try {
            Page<JobTask> tasks = jobTaskService.getAllTasks(pageable);
            return ResponseEntity.ok(ApiResponse.success("获取任务列表成功", tasks));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取任务列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取所有任务（不分页）
     */
    @GetMapping("/all")
    public ResponseEntity<?> getAllTasksNoPaging() {
        try {
            List<JobTask> tasks = jobTaskService.getAllTasks();
            return ResponseEntity.ok(ApiResponse.success("获取任务列表成功", tasks));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取任务列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据状态获取任务
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<?> getTasksByStatus(@PathVariable JobTask.TaskStatus status) {
        try {
            List<JobTask> tasks = jobTaskService.getTasksByStatus(status);
            return ResponseEntity.ok(ApiResponse.success("获取任务列表成功", tasks));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取任务列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取活跃任务
     */
    @GetMapping("/active")
    public ResponseEntity<?> getActiveTasks() {
        try {
            List<JobTask> tasks = jobTaskService.getActiveTasks();
            return ResponseEntity.ok(ApiResponse.success("获取活跃任务列表成功", tasks));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取活跃任务列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 启动任务
     */
    @PostMapping("/{id}/start")
    public ResponseEntity<?> startTask(@PathVariable Long id) {
        try {
            jobTaskService.startTask(id);
            return ResponseEntity.ok(ApiResponse.success("任务启动成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("启动任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 暂停任务
     */
    @PostMapping("/{id}/pause")
    public ResponseEntity<?> pauseTask(@PathVariable Long id) {
        try {
            jobTaskService.pauseTask(id);
            return ResponseEntity.ok(ApiResponse.success("任务暂停成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("暂停任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 恢复任务
     */
    @PostMapping("/{id}/resume")
    public ResponseEntity<?> resumeTask(@PathVariable Long id) {
        try {
            jobTaskService.resumeTask(id);
            return ResponseEntity.ok(ApiResponse.success("任务恢复成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("恢复任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 停止任务
     */
    @PostMapping("/{id}/stop")
    public ResponseEntity<?> stopTask(@PathVariable Long id) {
        try {
            jobTaskService.stopTask(id);
            return ResponseEntity.ok(ApiResponse.success("任务停止成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("停止任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * 立即执行任务
     */
    @PostMapping("/{id}/execute")
    public ResponseEntity<?> executeTaskNow(@PathVariable Long id) {
        try {
            jobTaskService.executeTaskNow(id);
            return ResponseEntity.ok(ApiResponse.success("任务执行成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("执行任务失败: " + e.getMessage()));
        }
    }
    
    /**
     * API响应封装类
     */
    public static class ApiResponse {
        private boolean success;
        private String message;
        private Object data;
        private long timestamp;
        
        public ApiResponse(boolean success, String message, Object data) {
            this.success = success;
            this.message = message;
            this.data = data;
            this.timestamp = System.currentTimeMillis();
        }
        
        public static ApiResponse success(String message) {
            return new ApiResponse(true, message, null);
        }
        
        public static ApiResponse success(String message, Object data) {
            return new ApiResponse(true, message, data);
        }
        
        public static ApiResponse error(String message) {
            return new ApiResponse(false, message, null);
        }
        
        public static ApiResponse error(String message, Object data) {
            return new ApiResponse(false, message, data);
        }
        
        // Getters
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
        public Object getData() { return data; }
        public long getTimestamp() { return timestamp; }
    }
}